package demo_0717;

// key-value 模型
public class T14_HashBucket_0410 {
    private static class Node {
        private int key;
        private int value;
        Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public int put(int key, int value) {
        // write code here

        int index = key % array.length;
        for (Node cur = array[index]; cur != null; cur = cur.next) {
            if (key == cur.key) {
                int oldValue = cur.value;
                cur.value = value;
                return oldValue;
            }
        }
        Node node = new Node(key, value);
        node.next = array[index];
        array[index] = node;
        size++;
        if (loadFactor() > LOAD_FACTOR) {
            resize();
        }
        return -1;
    }


    private void resize() {
        // write code here
        int len = array.length * 2;
        Node[] tmp = new Node[len];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                Node curNext = cur.next;
                int index = cur.key % len;
                cur.next = tmp[index];
                tmp[index] = cur;
                cur = curNext;
            }
        }
        array = tmp;
    }


    private double loadFactor() {
        return size * 1.0 / array.length;
    }


    public T14_HashBucket_0410() {
        // write code here
        array = new Node[DEFAULT_SIZE];
    }


    public int get(int key) {
        // write code here
        int index = key % array.length;
        Node head = array[index];
        for (Node cur = head; cur != null; cur = cur.next) {
            if (key == cur.key) {
                return cur.value;
            }
        }

        return -1;
    }
}
